package com.example.batterymonitoring;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView mText;
    Handler mHandler = new Handler();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mText = (TextView) findViewById(R.id.text);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);

        registerReceiver(mBatteryChangedReceiver, intentFilter);
    }

    private BroadcastReceiver mBatteryChangedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (TextUtils.equals(intent.getAction(), Intent.ACTION_BATTERY_CHANGED)) {
                final int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN);
                runOnUiThread(new Runnable() {
                    public void run() {
                        mText.append("\n");
                        switch (status) {
                        case BatteryManager.BATTERY_STATUS_FULL:
                            mText.append("BATTERY_STATUS_FULL");
                            break;
                        case BatteryManager.BATTERY_STATUS_CHARGING:
                            mText.append("BATTERY_STATUS_CHARGING");
                            break;
                        case BatteryManager.BATTERY_STATUS_DISCHARGING:
                            mText.append("BATTERY_STATUS_DISCHARGING");
                            break;
                        case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
                            mText.append("BATTERY_STATUS_NOT_CHARGING");
                            break;
                        case BatteryManager.BATTERY_STATUS_UNKNOWN:
                            mText.append("BATTERY_STATUS_UNKNOWN");
                            break;
                        }
                    }
                });
            }

        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}
